import { onMounted, onUnmounted, ref } from 'vue';

/**
 * 滚动触底 Hook（考虑滚动方向）
 * @param callback 触底时执行的回调函数
 * @param offset 触发回调的偏移量（距离底部多少像素视为触底，默认为0）
 * @returns 包含 isLoading 状态的 ref 对象
 */
export default function useScrollToBottom(
  callback: () => void,
  offset: number = 0
) {
  const isLoading = ref(false);
  let isExecuting = false;
  let lastScrollTop = 0;

  const handleScroll = async () => {
    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const clientHeight = document.documentElement.clientHeight;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;

    // 判断滚动方向（true表示向下滚动）
    const isScrollingDown = scrollTop > lastScrollTop;
    lastScrollTop = scrollTop;

    // 判断是否触底（考虑偏移量）
    const isBottom = scrollTop + clientHeight >= scrollHeight - offset;

    // 只有向下滚动且触底时才触发回调
    if (isScrollingDown && isBottom && !isExecuting) {
      isLoading.value = true;
      isExecuting = true;

      try {
        await callback();
      } finally {
        isLoading.value = false;
        isExecuting = false;
      }
    }
  };

  onMounted(() => {
    window.addEventListener('scroll', handleScroll);
    // 初始化 lastScrollTop
    lastScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
  });

  onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
  });

  return { isLoading };
}
